<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getAccountListApi, addAccountApi, editAccountApi } from '@/api/account'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'
import AccountDialog from './component/AccountDialog.vue'
import { useUserStore } from '@/stores/modules/user'

// 搜索表单
const searchForm = reactive({
  phoneNum: '',
  status: ''
})

// 表格数据
const tableData = ref([])

// 获取用户信息
const userStore = useUserStore()
const userInfo = userStore.userInfo

// 权限控制
const isSuperAdmin = computed(() => userInfo.identity === 1)
const canAddAccount = computed(() => isSuperAdmin.value)
const canEditAccount = computed(() => (row) => {
  if (isSuperAdmin.value) return true
  return row.id === userInfo.userId
})

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增账号')
const editData = ref({})



// 状态选项
const statusOptions = [
  { label: '全部', value: '' },
  { label: '正常', value: '0' },
  { label: '禁用', value: '1' }
]

// 身份映射
const identityMap = {
  1: '超级管理员',
  2: '普通管理员'
}

// 状态映射
const statusMap = {
  0: { text: '正常', type: 'success' },
  1: { text: '禁用', type: 'danger' }
}

// 获取账号列表
const getAccountList = async () => {
  try {
    const params = {
      ...searchForm
    }
    
    const res = await getAccountListApi(params)
    tableData.value = res
  } catch (error) {
    console.error('获取账号列表失败:', error)
    ElMessage.error('获取账号列表失败')
  } 
}

// 搜索
const handleSearch = () => {
  getAccountList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  getAccountList()
}

// 新增账号
const handleAdd = () => {
  if (!canAddAccount.value) {
    ElMessage.warning('您没有添加账号的权限')
    return
  }
  // 确保弹窗完全关闭后再打开
  if (dialogVisible.value) {
    dialogVisible.value = false
    setTimeout(() => {
      dialogTitle.value = '新增账号'
      editData.value = {}
      dialogVisible.value = true
    }, 200)
  } else {
    dialogTitle.value = '新增账号'
    editData.value = {}
    dialogVisible.value = true
  }
}

// 编辑账号
const handleEdit = (row) => {
  if (!canEditAccount.value(row)) {
    ElMessage.warning('您只能编辑自己的信息')
    return
  }
  // 确保弹窗完全关闭后再打开
  if (dialogVisible.value) {
    dialogVisible.value = false
    setTimeout(() => {
      dialogTitle.value = '编辑账号'
      editData.value = { ...row }
      dialogVisible.value = true
    }, 200)
  } else {
    dialogTitle.value = '编辑账号'
    editData.value = { ...row }
    dialogVisible.value = true
  }
}

// 弹窗确认
const handleDialogConfirm = async (formData) => {
  try {
    // 检查是否试图禁用自己
    if (editData.value.id && formData.status === 1 && editData.value.id === userInfo.userId) {
      ElMessage.warning('不能禁用自己')
      return
    }
    
    if (editData.value.id) {
      // 编辑模式
      await editAccountApi(formData)
      ElMessage.success('编辑成功')
    } else {
      // 新增模式
      await addAccountApi(formData)
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
    getAccountList() // 刷新列表
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 页面初始化
onMounted(() => {
  getAccountList()
})
</script>

<template>
  <div class="account-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-card>
        <div class="search-header">
          <div class="search-form">
            <el-form :model="searchForm" inline>
              <el-form-item label="手机号">
                <el-input
                  v-model="searchForm.phoneNum"
                  placeholder="请输入手机号"
                  clearable
                  style="width: 200px"
                />
              </el-form-item>
              
              <el-form-item label="用户状态">
                <el-select
                  v-model="searchForm.status"
                  placeholder="请选择状态"
                  clearable
                  style="width: 200px"
                >
                  <el-option
                    v-for="item in statusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="handleSearch">
                  <el-icon><Search /></el-icon>
                  搜索
                </el-button>
                <el-button @click="handleReset">
                  <el-icon><Refresh /></el-icon>
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          
          <div class="search-actions">
            <el-button 
              type="primary" 
              @click="handleAdd"
              :disabled="!canAddAccount"
            >
              <el-icon><Plus /></el-icon>
              新增账号
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-card>
        <el-table
          :data="tableData"
          stripe
          style="width: 100%"
          max-height="500"
          class="compact-table"
        >
                     <el-table-column prop="id" label="ID" width="120" align="center" />
          
          <el-table-column prop="identity" label="身份" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="row.identity === 1 ? 'danger' : 'primary'">
                {{ identityMap[row.identity] || '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="phoneNumber" label="手机号" width="150" align="center" />
          
          <el-table-column prop="nickName" label="昵称" align="center" />
          
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusMap[row.status]?.type || 'info'">
                {{ statusMap[row.status]?.text || '未知' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
          
          <el-table-column label="操作" width="250" fixed="right" align="center">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="default" 
                @click="handleEdit(row)"
                :disabled="!canEditAccount(row)"
              >
                编辑
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <!-- 弹窗组件 -->
    <AccountDialog
      v-model:visible="dialogVisible"
      :title="dialogTitle"
      :edit-data="editData"
      :is-current-user="editData.id === userInfo.userId"
      @confirm="handleDialogConfirm"
    />
  </div>
</template>

<style scoped lang="scss">
.account-container {
  padding: 20px;
  
  .search-section {
    margin-bottom: 20px;
    
    .search-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      
      .search-form {
        flex: 1;
      }
      
      .search-actions {
        margin-left: 20px;
      }
    }
  }
  
  .table-section {
    .compact-table {
      :deep(.el-table__body-wrapper .el-table__row) {
        height: 50px !important;
      }
      
      :deep(.el-table__cell) {
        padding: 8px 0 !important;
      }
    }
    
    // 全局表格行高设置
    :deep(.el-table .el-table__body-wrapper .el-table__row) {
      height: 50px !important;
    }
  }
}
</style>